<template>
  <el-dialog
    v-el-drag-dialog
    class="activity-dialog"
    :title="type | titleText"
    :visible.sync="isShow"
    width="700px"
    @closed="close"
  >
    <el-form
      ref="dataForm"
      class="form"
      :rules="rules"
      :model="form"
      label-position="right"
      label-width="140px"
    >
      <el-form-item label="规则描述:" prop="reguName">
        <el-input v-model="form.reguName" :disabled="type === 3" />
      </el-form-item>
      <el-form-item label="规则生效时间:" prop="date">
        <el-date-picker
          v-model="form.date"
          :disabled="type === 3"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="适用机构:" prop="orgSNNo">
            <el-tree-select
              v-model="form.orgSNNo"
              :disabled="type === 3"
              :clearable="false"
              class="tree-select"
              :popover-width="360"
              :select-params="{
                clearable: true,
                placeholder: '请选择适用机构',
                loading: $loadingPlugin.getTreeData,
              }"
              :tree-params="{
                'default-expand-all': true,
                'expand-on-click-node': false,
                'highlight-current': true,
                props: {
                  value: 'orgSNNo',
                  label: 'orgName',
                  disabled: 'disabled',
                },
                data: treeData,
              }"
              @node-click="selectTreeChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="适用渠道:" prop="linePage">
            <el-checkbox-group v-model="form.linePage" :disabled="type === 3">
              <el-checkbox :label="1">线上</el-checkbox>
              <el-checkbox :label="2">线下</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div v-if="type !== 3" class="activity-dialog_btn">
      <el-button size="mini" type="primary" @click="add">添加</el-button>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      header-row-class-name="table-row-name"
      :column="column"
      :data="tableData"
      custom-column
      @fetch="fetchData"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="close"> 关闭 </el-button>
      <el-button
        v-if="type === 1 || type === 2"
        :loading="$loadingPlugin.add || $loadingPlugin.edit"
        type="primary"
        @click="save"
      >
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import moment from 'dayjs'
  import { rechargeRuleAdd, rechargeRuleUpdate, rechargeRuleDetail } from '@/api'
  export default {
    name: 'activityDialog',
    filters: {
      titleText(val) {
        switch (val) {
        case 1:
          return '新增金额充值规则'
        case 2:
          return '编辑金额充值规则'
        case 3:
          return '规则详情'
        }
      }
    },

    props: {
      treeData: {
        type: Array
      }
    },
    data() {
      return {
        isShow: false,
        form: {
          orgSNNo: '', // 适用机构编号
          orgName: '', // 适用机构名称
          reguName: '', // 规则描述
          linePage: [1, 2], // 适用规则渠道
          date: '' // 规则生效时间
        },
        rules: {
          reguName: [{ required: true, message: '请输入规则描述', trigger: 'change' }],
          date: [{ required: true, message: '请输入规则生效时间', trigger: 'change' }],
          orgSNNo: [{ required: true, message: '请输入规则适用机构', trigger: 'change' }],
          linePage: [{ required: true, message: '请选择规则适用渠道', trigger: 'change' }]
        },
        type: 1,
        tableData: [],
        tableDefaultData: [],
        reguId: ''
      }
    },
    computed: {
      column: function() {
        const column = [
          {
            type: 'index'
          },
          {
            prop: 'feeCount1',
            label: '充值金额满(￥)',
            render: (h, scope) => {
              return (
              <div>
                {scope.row._edit ? (
                  <el-input
                    value={scope.row[scope.column.property]}
                    maxlength={8}
                    onInput={(val) => {
                      scope.row[scope.column.property] = val.replace(/[^\d.]/g, '')
                    }}
                  ></el-input>
                ) : (
                  <span>{scope.row[scope.column.property]}</span>
                )}
              </div>
              )
            }
          },
          {
            prop: 'feeCount2',
            label: '赠送(￥)',
            render: (h, scope) => {
              return (
              <div>
                {scope.row._edit ? (
                  <el-input
                    value={scope.row[scope.column.property]}

                    onInput={(val) => {
                      scope.row[scope.column.property] = val.replace(/[^\d.]/g, '')
                    }}
                  ></el-input>
                ) : (
                  <span>{scope.row[scope.column.property]}</span>
                )}
              </div>
              )
            }
          },
          {
            label: '操作',
            className: 'action-col',
            width: 165,
            fixed: 'right',
            align: 'center',
            render: (h, scope) => {
              return (
              <div>
                {scope.row._edit ? (
                  <el-link
                    type='primary'
                    onClick={() => {
                      this.handleSave(scope)
                    }}
                  >
                    结束编辑
                  </el-link>
                ) : (
                  <el-link
                    type='primary'
                    onClick={() => {
                      this.handleEdit(scope)
                    }}
                  >
                    编辑
                  </el-link>
                )}
                <el-link
                  size='mini'
                  underline={false}
                  type='danger'
                  onClick={() => this.del(scope.$index)}
                >
                  删除
                </el-link>
              </div>
              )
            }
          }
        ]
        if (this.type !== 3) return column
        else {
          // 3 是规则详情 没有操作栏
          column.pop()
          return column
        }
      }
    },
    methods: {
      fetchData() {},
      selectTreeChange(value) {
        this.form.orgSNNo = value.orgSNNo
        this.form.orgName = value.orgName
      },
      show(type, data) {
        // type 1 新增 2 编辑  3 查看详情
        this.type = type
        this.isShow = true

        if (type === 2 || type === 3) {
          this.form.reguName = data.remark // 编辑和新增 修改的值不一样 一个是remark， reguName
          this.form.orgSNNo = data.orgSNNo
          this.form.orgName = data.orgName
          if (data.linePage === 3) this.form.linePage = [1, 2]
          else this.form.linePage.push(data.linePage)
          this.form.date = [data.beginDt, data.endDt]
          this.reguId = data.reguId

          this.getDetailData(data.reguId)
        }
      },
      // 获取规则详情
      async getDetailData(reguId) {
        const params = {
          reguId: reguId
        }
        const { status, data } = await rechargeRuleDetail(params)
        if (status === 200) {
          this.tableData = data.accCsmCardRcReGuDetailInfoList.map((v) => {
            return {
              feeCount1: (v.feeCount1 / 100).toFixed(2),
              feeCount2: (v.feeCount2 / 100).toFixed(2),
              reguId: v.reguId
            }
          })
        }
      },
      save() {
        this.$refs.dataForm.validate((valid) => {
          if (!valid) return
          // 判断是否未添加规则
          if (!this.tableData.length) {
            this.$message.error('您还未添加任何金额充值规则信息')
            return
          } else {
            // 判断规则中是否有 为0的
            for (let i = 0; i < this.tableData.length; i++) {
              if (!Number(this.tableData[i].feeCount1)) {
                this.$message.error('请输入充值金额')
                return
              }
              if (!Number(this.tableData[i].feeCount2)) {
                this.$message.error('请输入赠送金额')
                return
              }
            }
          }
          this.submit()
        })
      },
      submit() {
        const params = {
          reguId: this.type === 2 ? this.reguId : undefined, // 编辑需要规则id
          reguName: this.form.reguName, // 规则描述
          rcType: 1, // 规则类型
          beginDt: moment(this.form.date[0]).format('YYYY-MM-DD'), // 规则生效开始时间
          endDt: moment(this.form.date[1]).format('YYYY-MM-DD'), // 规则生效结束时间
          orgSNNo: this.form.orgSNNo, // 适用机构编号
          orgName: this.form.orgName, // 适用机构名称
          linePage: this.form.linePage.length === 2 ? 3 : this.form.linePage[0], // 使用规则渠道
          accCsmCardRcReGuDetailInfoList: this.tableData.map((v) => {
            // 规则详情
            return {
              feeCount1: v.feeCount1 * 100,
              feeCount2: v.feeCount2 * 100,
              reguId: v.reguId
            }
          })
        }

        if (this.type === 1) this.submitAdd(params)
        else this.submitEdit(params)
      },
      // 添加规则
      async submitAdd(params) {
        const { status } = await rechargeRuleAdd(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: `新增规则成功`,
            type: 'success',
            duration: 2000
          })
          this.$emit('refresh')
          this.close()
        }
      },
      // 修改规则
      async submitEdit(params) {
        params.remark = params.reguName
        delete params.reguName
        const { status } = await rechargeRuleUpdate(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: `编辑规则成功`,
            type: 'success',
            duration: 2000
          })
          this.$emit('refresh')
          this.close()
        }
      },
      close() {
        this.isShow = false
        this.tableData = []
        this.$refs['dataForm'].resetFields()
      },
      add() {
        const defalutData = {
          feeCount1: '0.00',
          feeCount2: '0.00'
        }
        this.tableData.push(defalutData)
      },
      del(index) {
        this.tableData.splice(index, 1)
      },
      handleSave(scope) {
        // 充值和活动金额最大为 10000
        if (scope.row.feeCount1 > 10000) this.$set(scope.row, 'feeCount1', '10000.00')
        if (scope.row.feeCount2 > 10000) this.$set(scope.row, 'feeCount2', '10000.00')
        if (!scope.row.feeCount1) {
          this.$message.error('请输入充值金额')
          return
        } else {
          this.$set(scope.row, 'feeCount1', ((scope.row.feeCount1 * 100) / 100).toFixed(2))
        }
        if (!scope.row.feeCount2) {
          this.$message.error('请输入奖励金额')
          return
        } else {
          this.$set(scope.row, 'feeCount2', ((scope.row.feeCount2 * 100) / 100).toFixed(2))
        }

        // 当前编辑行数据
        const rowFeeCount1 = scope.row.feeCount1
        const rowFeeCount2 = scope.row.feeCount2

        for (let index = 0; index < this.tableData.length; index++) {
          const feeCount1 = this.tableData[index].feeCount1
          const feeCount2 = this.tableData[index].feeCount2

          if (index !== scope.$index) {
            // 校验充值金额不可相同
            if (rowFeeCount1 === feeCount1) {
              this.$message.error('存在至少2条充值金额相同数据')
              return
            }
            // 校验充值金额大，优惠活动却小
            if (
              Number(feeCount1) < Number(rowFeeCount1) &&
              Number(rowFeeCount2) <= Number(feeCount2)
            ) {
              this.$message.error('存在充值金额大,但赠送金额却不大于的情况')
              return
            }
            // 校验充值金额小，优惠活动却大
            if (
              Number(feeCount1) >= Number(rowFeeCount1) &&
              Number(rowFeeCount2) >= Number(feeCount2)
            ) {
              this.$message.error('存在充值金额小,但赠送金额却不小于的情况')
              return
            }
          }
        }

        this.$set(scope.row, '_edit', false)
      },
      // 开启编辑
      handleEdit(scope) {
        if (Number(scope.row.feeCount1) === 0) this.$set(scope.row, 'feeCount1', '')
        if (Number(scope.row.feeCount2) === 0) this.$set(scope.row, 'feeCount2', '')
        this.$set(scope.row, '_edit', true)
      }
    }
  }
</script>

<style lang="scss" scoped>
.activity-dialog {
  /deep/.el-dialog {
    .el-date-editor {
      width: 100%;
    }
  }
  .activity-dialog_btn {
    margin-bottom: 10px;
  }
}
</style>
